`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: Liuxiang from yancheng
// 
// Create Date:    14:47:34 01/16/2013 
// Design Name: 
// Module Name:    SD_TOP 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module SD_TOP(
					input  clk_85m,
					input  rst,
					input  clk_25m,
					output SD_clk,
					output reg SD_cs,
					output reg SD_datain,
					input  SD_dataout,
					output sd_rd_done,
					output ui_wr,
					output [23:0] ui_wr_data,
					output [25:0] ui_addr,
					input [31:0] all_pixel,
					input [31:0] all_fats,  
					input ui_ready,
					input [31:0]start_add_data,
					output done,
					input rx_ok_data,
					input [3:0]bmp_num1
					
    );
	 


wire [31:0]read_sec;
wire read_SD;

wire [7:0]mydata_o;
wire myvalid_o;

wire [7:0]rx_o;
wire init_o;
wire read_o;
reg start_sd_read;
reg start_sd_clk;
//assign SD_clk = ~clk_25m;
assign SD_clk =sd_rd_done ?  1'bz  : (start_sd_clk ? ~clk_25m : 1'bz);
assign done = sd_rd_done ? 1'b0 : 1'b1;
//assign done = sd_rd_done;
always @(posedge clk_25m or posedge rst) begin
  if(rst) begin
    start_sd_read <= 1'b0;
	 start_sd_clk <=1'b0;
  end 
  else if(init_o && ui_ready) begin
    start_sd_read <= 1'b1; 
	 end
  else if(rx_ok_data) begin
		start_sd_clk <=1'b1;
	
  end
end

SD_initial	SD_initial_inst(
						
						.rst(rst),
						.SD_clk(clk_25m),
						.SD_cs(SD_cs_i),
						.SD_datain(SD_datain_i),
						.SD_dataout(SD_dataout),
						.rx(),
						.init_o(init_o)

);


	 
SD_read	SD_read_inst(   
						.SD_clk(clk_25m),
						.SD_cs(SD_cs_r),
						.SD_datain(SD_datain_r),
						.SD_dataout(SD_dataout),
						
						.sec(read_sec),
						.read_req(read_SD),
						.mydata_o(mydata_o),
						.myvalid_o(myvalid_o),
						
						.data_come(data_come),
						
						.init(start_sd_read),
						
						.rx(rx_o)
						
						
    );



always @(posedge clk_25m)
begin
	if(sd_rd_done==1'b1) begin
		SD_cs<=1'bz;
		SD_datain<=1'bz;
	end
	else begin
		if(start_sd_clk==1'b0) begin
				SD_cs<=1'bz;
				SD_datain<=1'bz;	
		end
		else  begin
		if(!init_o)
			begin
				SD_cs<=SD_cs_i;
				SD_datain<=SD_datain_i;
			end
		else
			begin
				SD_cs<=SD_cs_r;
				SD_datain<=SD_datain_r;
			end
		end
	end
end


ram_rw_control ram_rw_control_inst(
	.clk_85m(clk_85m),
	.SD_clk(clk_25m),
	.rst(rst),
	.init(init_o),
	.data_come(data_come),
	.read_sec(read_sec),
	.read_SD(read_SD),
	.mydata(mydata_o),
	.myvalid(myvalid_o),
	.sd_rd_done(sd_rd_done),
	.ui_ready(ui_ready),
	.ui_wr(ui_wr),
	.ui_wr_data(ui_wr_data),
					.all_pixel(all_pixel),
					.all_fats(all_fats),
	.ui_wr_addr(ui_addr),
	.start_add_data(start_add_data),
	.bmp_num1(bmp_num1)
);
    

endmodule
